package com.zll.onlineExam.ajax;

import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zll.onlineExam.utils.StringUtil;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @name Ajax
 * @date 2022/3/5 16:46
 */
public class Ajax {

    private static String token;
    private static Ajax instance;
    private static String baseUrl;
    private static OkHttpClient client;
    private static String contentType = "application/json;charset=utf-8";

    private static final String TAG = "===AJAX";


    // 单例模式
    private static void init() {
        if (instance == null) {
            instance = new Ajax();
            baseUrl = HTTPConfig.API;
            client = new OkHttpClient().newBuilder().
                    retryOnConnectionFailure(false).
                    connectTimeout(20, TimeUnit.SECONDS).
                    readTimeout(20, TimeUnit.SECONDS).
                    writeTimeout(20, TimeUnit.SECONDS).
                    build();
        }
    }

    public static boolean hasToken() {
        return StringUtil.isNotBlank(token);
    }

    public static void setToken(String str) {
        Log.d(TAG, "setToken: " + str);
        if (StringUtil.isNotBlank(str)) {
            token = str;
        }
    }

    public static void cleanToken(){
        token = "";
    }

    private static Headers genHeader() {
        Headers.Builder headers = new Headers.Builder();
        if (hasToken()) {
            headers.add("Authorization", token);
        }
        headers.add("ContentType", contentType);
        return headers.build();
    }

    public static void get(String url, Map<String, Object> param, ReqCallback callback) {

    }

    public static void post(String url, Map<String, Object> data, ReqCallback callback) {
        Ajax.init();
        JSONObject jsonObject = new JSONObject(data);
        Log.d(TAG, "=== begin post ==="+url);
        Log.d(TAG, "body: "+jsonObject.toJSONString());
        RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), jsonObject.toJSONString());
        Request request = new Request.Builder()
                .url(baseUrl + url)
                .post(requestBody)
                .headers(genHeader())
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG,"onError"+" : "+e.getMessage());
                e.printStackTrace();
                callback.onError(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String res = response.body().string();
                Log.d(TAG,url+" : "+res);
                JSONObject resp = JSON.parseObject(res);
                // 如果是成功code为0000
                if (resp.getString("code").equals("0000")){
                    Log.d(TAG,"onSuccess"+" : "+resp.getString("data"));
                    callback.onSuccess(resp);
                }else{
                    Log.d(TAG,"onFail"+" : "+resp.getString("msg"));
                    callback.onFail(resp.getString("msg"));
                }

            }
        });
        Log.d(TAG, "headers: " + request.headers().toString());

    }

}
